#include "ModelManager.h"

ModelManager::ModelManager(CGparameter matrixParam)
{
	this ->matrixParam = matrixParam;
}

ModelManager::~ModelManager(void)
{
}

void ModelManager::Load(const char *path, const char *ext)
{
	std::string searchPath = path;
	searchPath += "\\*.";
	searchPath += ext;

	WIN32_FIND_DATA fd;

	HANDLE hfile = FindFirstFile(searchPath.c_str(), &fd);
	if (hfile != INVALID_HANDLE_VALUE)
	{
		BOOL doSearch = true;
		while (doSearch)
		{
			std::string modelPath = path;
			modelPath += "\\";
			modelPath += fd.cFileName;
			
			sgm::Geometry *geo = sgm::SGMLoader::LoadFromFile(modelPath.c_str());
			Model *model = new Model(geo, matrixParam);

			std::string modelFileName = fd.cFileName;
			Add(modelFileName.substr(0, modelFileName.size() - 4).c_str(), model);

			doSearch = FindNextFile(hfile, &fd);
		}

		FindClose(hfile);
	}
}

void ModelManager::Add(const char *name, Model *res)
{
	models[name] = res;
}

Model * ModelManager::Get(const char *name)
{
	std::map<std::string, Model*>::iterator i = models.find(name);
	if (i == models.end())
		return NULL;

	return (*i).second;
}

int ModelManager::GetCount()
{
	return (int)models.size();
}

void ModelManager::Get(int i, char *name, Model *&res)
{
	std::map<std::string, Model*>::iterator it = models.begin();
	while (i--)
		it ++;

	strcpy(name, (*it).first.c_str());
	res = (*it).second;
}
